﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoolanSlide.FileStruct;
using BoolanSlide.Language;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;

namespace BoolanElement.Storage
{
    public delegate void CompletedRename(List<BPTFileInformation> bptFileList);
    public class EditFileInfo
    {
        private Popup showPopup;
        private TextBlock textPrompt;
        private TextBox textFileName;
        private Button commitButton;
        private Button closeButton;
        private List<BPTFileInformation> bptFileList;
        private int currentFileIndex;

        public CompletedRename completedRename;
        private bool canRecordNewFileName;

        public EditFileInfo()
        {
            showPopup = new Popup();
          

            InitializeTextPrompt();
            InitailizeTextFileName();
            InitializeCommitButton();
            InitializeCloseButton();


            InitializeShowPopup();

            canRecordNewFileName = true;
            currentFileIndex = -1;
        }

        private void InitializeTextPrompt()
        {
            textPrompt = new TextBlock();
 
            textPrompt.Foreground = new SolidColorBrush(Color.FromArgb(255, 17, 122, 168));
            textPrompt.FontFamily = new FontFamily("微软雅黑");
            textPrompt.Text = LanguageManager.PleaseInputNewFileName;
        }

        private void InitailizeTextFileName()
        {
            textFileName = new TextBox();
            textFileName.FontSize = 22;
            textFileName.TextAlignment = TextAlignment.Left;         
            textFileName.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            textFileName.TextChanged += textFileName_TextChanged;
            textFileName.KeyUp += textFileName_KeyUp;
        }

        private void InitializeCloseButton()
        {
            closeButton = new Button();
            closeButton.Content = LanguageManager.CancelButton;
            closeButton.Background = new SolidColorBrush(Color.FromArgb(255, 17, 122, 168));
            closeButton.Click += CloseButton_Click;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            showPopup.IsOpen = false;
         
        }
        private void InitializeCommitButton()
        {
            commitButton = new Button();

            commitButton.Content = LanguageManager.ConfirmButton;          
            commitButton.Background = new SolidColorBrush(Color.FromArgb(255, 17, 122, 168));
            commitButton.Click += CommitButton_Click;
           // commitButton.IsEnabled = false;
        }

        private async void CommitButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (IsExist(textFileName.Text) == true)
                return;

            if (IsNameEmpty(textFileName.Text) == true)
                return;

            if (textFileName.Text.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
            {
                textPrompt.Text = LanguageManager.CharacterNotAllowed;
                return;
            }

            await Rename(bptFileList[currentFileIndex].FileName);
            showPopup.IsOpen = false;
        }



        void textFileName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (canRecordNewFileName == true && commitButton.IsEnabled == false)
            {
                commitButton.IsEnabled = true;
            }
            textPrompt.Text = LanguageManager.PleaseInputNewFileName;
            textPrompt.Foreground = new SolidColorBrush(Color.FromArgb(255, 17, 122, 168));
        }

        void textFileName_KeyUp(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
                CommitButton_Click(null, null);
        }


        private void SetChildrenLocation()
        {
            ////重命名提示语
            textPrompt.FontSize = 22;
            textPrompt.Height = 40;
            textPrompt.Width = 600;
            textPrompt.Height = 40;
            textPrompt.Margin = new Thickness(0, 20, 0, 0);
            textPrompt.TextAlignment = TextAlignment.Center;
            
            //文本输入框
            textFileName.Width = 400;
            textFileName.Height = 40;
            textFileName.Margin = new Thickness(0, 10, 0, 0);

            //确定
            commitButton.Width = 100;
            commitButton.Height = 40;
            closeButton.Margin = new Thickness(0, 0, 0, 0);

            //取消
            closeButton.Width = 100;
            closeButton.Height = 40;
            closeButton.Margin = new Thickness(20, 0, 0, 0);        
        }

        private void InitializeShowPopup()
        {
            //当前屏幕宽
            double screenWidth = Window.Current.CoreWindow.Bounds.Width;
            //当前屏幕高
            double screenHeight = Window.Current.CoreWindow.Bounds.Height;

            SetChildrenLocation();
            //遮罩
            Canvas markCanvas = new Canvas();
            markCanvas.Width = screenWidth;
            markCanvas.Height = screenHeight;
            markCanvas.Background = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));

           
            
            StackPanel showStackPanel = new StackPanel();
            showStackPanel.Background = new SolidColorBrush(Color.FromArgb(200, 193, 222, 238));
            StackPanel stackPanel = new StackPanel();
            showStackPanel.Width = screenWidth;
            showStackPanel.Margin = new Thickness(0,260,0,0);
            showStackPanel.Height = 200;
            stackPanel.Orientation = Orientation.Vertical;

             stackPanel.Children.Add(textPrompt);
             stackPanel.Children.Add(textFileName);

            StackPanel commitStackPanel = new StackPanel();

            commitStackPanel.Width = 400;
            commitStackPanel.Height = 40;
            commitStackPanel.Margin = new Thickness(0, 20,0, 0);
            //commitStackPanel.Background = new SolidColorBrush(Color.FromArgb(180,244,245,249));
             commitStackPanel.Orientation = Orientation.Horizontal;         
            commitStackPanel.Children.Add(commitButton);
            commitStackPanel.Children.Add(closeButton);

            textFileName.TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap;
            textFileName.MaxLength = 128;
            

            stackPanel.Children.Add(commitStackPanel);
            showStackPanel.Children.Add(stackPanel);

            markCanvas.Children.Add(showStackPanel);
            showPopup.Child = markCanvas;


            canRecordNewFileName = true;
        }

        public void Eidt(string strOriginalFileName, List<BPTFileInformation> bptList)
        {
            bptFileList = bptList;
            for (int i = 0; i < bptList.Count; i++)
            {
                if (bptList[i].FileName == strOriginalFileName)
                {
                    currentFileIndex = i;
                    break;
                }
            }

            string []FileNameAndFilter = strOriginalFileName.Split('.');
         
            textFileName.Text = FileNameAndFilter[0];
            showPopup.IsOpen = true;
            commitButton.Content = LanguageManager.ConfirmButton;
            closeButton.Content = LanguageManager.CancelButton;
            textPrompt.Text = LanguageManager.PleaseInputNewFileName;
            textFileName.Focus(FocusState.Keyboard);
            textFileName.SelectionStart = textFileName.Text.Length;
        }

        public void SetShowPosition(double horizontalOffSet, double verticalOffSet)
        {
            showPopup.HorizontalOffset = horizontalOffSet;
            showPopup.VerticalOffset = verticalOffSet;
        }
        
        private async Task<bool> Rename(string OriginalFileName)
        {
            string newFileName = this.textFileName.Text;
            newFileName += Configuration.GlobalVariable.FileExtension;
            
            if (newFileName == OriginalFileName)
                return true;

            if (textFileName.Text.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
            {
                textPrompt.Text = LanguageManager.CharacterNotAllowed;
                return true;
            }

            StorageFolder folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.LibraryFolder);

            StorageFile file = await folder.GetFileAsync(OriginalFileName);

            await file.RenameAsync(newFileName);

            bptFileList[currentFileIndex].FileName = newFileName;

            completedRename(bptFileList);

            return true;
        }

        private bool IsExist(string newFileName)
        {
            newFileName = textFileName.Text + Configuration.GlobalVariable.FileExtension;
            for (int i = 0; i < bptFileList.Count; i++)
            {

                string newFileNameTemp = newFileName.ToLower();
                string FileNameTemp = bptFileList[i].FileName.ToLower();

                if (newFileNameTemp == FileNameTemp)
                {
                    textPrompt.Text = "已存在同名文件，请重新输入名字:";
                    textFileName.Focus(FocusState.Keyboard);
                    textFileName.SelectionStart = textFileName.Text.Length;
                    return true;
                }
            }
            return false;
        }

        private bool IsNameEmpty(string newFileName)
        {
            if (newFileName.Length == 0)
            {
                textPrompt.Text = LanguageManager.FileCanNotBeNull;
                textFileName.Focus(FocusState.Keyboard);
                return true;
            }
            return false;
        }

        private async void DeleteButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            StorageFolder folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.LibraryFolder);

            StorageFile file = await folder.GetFileAsync(bptFileList[currentFileIndex].FileName);

            await file.DeleteAsync();

            bptFileList.RemoveAt(currentFileIndex);

            completedRename(bptFileList);

            showPopup.IsOpen = false;
        }
    }
}
